package flc.ast.widget.calendar;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.blankj.utilcode.util.Utils;
import com.stark.appwidget.lib.AppWidgetViewManager;
import com.stark.appwidget.lib.BaseAppWidgetView;

import stark.common.basic.utils.BroadcastReceiverUtil;

public abstract class BaseCalendarWidget extends BaseAppWidgetView {
    public BaseCalendarWidget(int appWidgetId) {
        super(appWidgetId);
        registerReceiver();
    }

    @Override
    public void update(Context context) {
        registerReceiver();
        onUpdate(context);
    }

    protected abstract void onUpdate(Context context);

    @Override
    public void destroy() {
        unregisterReceiver();
    }

    private BroadcastReceiver mReceiver;

    private void registerReceiver() {
        if (mReceiver == null) {
            mReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    AppWidgetViewManager.getInstance().updateAppWidgetView2Db(BaseCalendarWidget.this);
                    update(context);
                }
            };
            IntentFilter filter = new IntentFilter();
            BroadcastReceiverUtil.registerReceiver(mReceiver, filter);
        }
    }

    private void unregisterReceiver() {
        if (mReceiver != null) {
            BroadcastReceiverUtil.unregisterReceiver(mReceiver);
            mReceiver = null;
        }
    }
}
